//
//  YDFOAuthViewController.swift
//  weibo20
//
//  Created by mac on 16/1/23.
//  Copyright © 2016年 tingyuyisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 用户登陆授权页面
class YDFOAuthViewController: UIViewController {

	private lazy var webView = UIWebView()

	// MARK: - 监听方法
	@objc private func close() {
		dismissViewControllerAnimated(true, completion: nil)
		SVProgressHUD.dismiss()
	}
	@objc private func autoFill() {

		let JSString = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
			"document.getElementById('passwd').value = 'qqq123';"
		webView.stringByEvaluatingJavaScriptFromString(JSString)
	}

	override func loadView() {
		view = webView
		webView.delegate = self
		setupNav()
	}

	override func viewDidLoad() {
		super.viewDidLoad()
		// 加载页面
		webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthURL))
	}

	/// 设置导航栏按钮
	private func setupNav() {
		title = "登录到新浪微博"
		navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
		navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
	}

	// MARK: - 加载授权页面
}

// MARK: - UIWebViewDelegate
extension YDFOAuthViewController : UIWebViewDelegate {

	func webViewDidStartLoad(webView: UIWebView) {
		SVProgressHUD.showWithStatus("别着急...正在加载呢...", maskType: .Gradient)
	}
	func webViewDidFinishLoad(webView: UIWebView) {
		SVProgressHUD.dismiss()
	}
	/// 将要加载请求的web代理方法
	///
	/// - parameter webView:        webView description
	/// - parameter request:        将要加载的请求
	/// - parameter navigationType: navigationType description
	///
	/// - returns: return value description
	func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

		guard let url = request.URL where url.host == "www.baidu.com" else {

			return true
		}

		guard let query = url.query where query.hasPrefix("code=") else {
			print("取消授权")
			return false
		}

		// 字符串截取
		let codeStr = "code="
		let code = query.substringFromIndex(codeStr.endIndex)

		/// 加载
		NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in

			if error != nil {
				print(error)
				return
			}
			print(result)
			let account = userAccount(dict: result as! [String: AnyObject])
            print(account)
			self.close()
		}

//		print(url.host)
//		print(url.query)
//		print(url.absoluteString)

		return false
	}
}
